package servlet;

import dao.NewsDao;
import model.News;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;

@WebServlet(urlPatterns = "/NewsServlet.do")
@MultipartConfig
public class NewsServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        NewsDao newsDao = null;
        try {
            newsDao = new NewsDao();
            List<News> newsList = newsDao.getAllNews();
            HttpSession session = request.getSession();
            session.setAttribute("newsList", newsList);
            response.sendRedirect(request.getContextPath() + "/admin/NewsView.jsp");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String uploadPath = "B:\\javaweb\\PressRelease-v1.3\\src\\main\\webapp\\image"; // 上传文件的保存路径
        File uploadDir = new File(uploadPath);

        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String author = request.getParameter("author");
        Part filePart = request.getPart("image");

        String fileName = filePart.getSubmittedFileName();

        try (InputStream fileContent = filePart.getInputStream();
             FileOutputStream fos = new FileOutputStream(uploadPath + File.separator + fileName)) {
            int read;
            final byte[] bytes = new byte[1024];
            while ((read = fileContent.read(bytes)) != -1) {
                fos.write(bytes, 0, read);
            }
        }

        try {
            NewsDao newsDao = new NewsDao(); // 假设 NewsDao 负责与数据库交互
            News news = new News();
            news.setAuthor(author);
            news.setImagePath("image/" + fileName);
            news.setContent(content);
            news.setTitle(title);

            boolean saveNews = newsDao.saveNews(news.getTitle(),news.getAuthor(),news.getContent(),news.getImage_Path());

            if (saveNews) {
                response.sendRedirect(request.getContextPath() + "/NewsServlet.do");
            } else {
                response.sendRedirect(request.getContextPath() + "/home/404.html");
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }
}
